using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using GrailTechnology.AutoTags.Providers;
using log4net;
using System.Reflection;
using umbraco.cms.businesslogic.Tags;

namespace GrailTechnology.AutoTags.DataType
{
    public partial class AutoTags : UserControl, umbraco.editorControls.userControlGrapper.IUsercontrolDataEditor
    {
        private static readonly ILog Log_ = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private List<Tag> _allTags;

        public string SpinnerImage;

        private static int CurrentNodeId
        {
            get;
            set;
        }

		private string GroupName
		{
			get { return !string.IsNullOrEmpty(Config.Instance.TagGroup) ? Config.Instance.TagGroup : "GrailTechTags"; }
		}
        
        public bool GenerateAutomatically
        {
            get { return Config.Instance.GenerateTagsAutomatically; }
        }

        public bool AllowManualTags
        {
            get { return Config.Instance.AllowManualTags; }
        }

        protected string PropertyAliasesToUse
        {
            get { return Config.Instance.PropertyAliasesToUse; }
        }

        protected string PropertyAliasesToExclude
        {
            get { return Config.Instance.PropertyAliasesToExclude; }
        }

        protected override void OnInit(EventArgs e)
        {
            Log_.Debug("Initialising usercontrol");
            CurrentNodeId = Convert.ToInt32(Request["id"]);

            Log_.Debug(umbraco.GlobalSettings.Path);

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("autotag"))
            {
                Page.ClientScript.RegisterClientScriptInclude(GetType(), "autotag",
                                                              ResolveClientUrl(umbraco.GlobalSettings.Path +
                                                                               Config.PluginPath +
                                                                               "/scripts/autoTags.js"));
            }

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("jqueryform"))
            {
                Page.ClientScript.RegisterClientScriptInclude(GetType(), "jqueryform",
                                                              ResolveClientUrl(umbraco.GlobalSettings.Path +
                                                                               Config.PluginPath +
                                                                               "/scripts/jquery.form.js"));
            }

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("autogrow"))
            {
                Page.ClientScript.RegisterClientScriptInclude(GetType(), "autogrow",
                                                              ResolveClientUrl(umbraco.GlobalSettings.Path +
                                                                               Config.PluginPath +
                                                                               "/scripts/jquery.autogrow.js"));
            }

            SpinnerImage = ResolveClientUrl(umbraco.GlobalSettings.Path + Config.PluginPath + "/images/ajax-loader.gif");


            Literal1.Text = "<link rel=\"Stylesheet\" type=\"text/css\" href=\"" +
                            ResolveClientUrl(umbraco.GlobalSettings.Path + Config.PluginPath + "/css/tags.css") + "\"/>" +
                            Environment.NewLine;

            if (!Config.Instance.AllowTagSuggestion)
            {
                buttonGetTags.Visible = false;
            }

            if (!Config.Instance.ShowHelp)
            {
                viewHelp.Visible = false;
            }
        }


        private string _umbracoValue;
        protected void Page_Load(object sender, EventArgs e)
        {
            Log_.Debug("Rendering userControl");
            
            if (IsPostBack)
            {
                Log_.Debug("active tags: " + ActiveTags.Value);
                AddTagsToNode();
            }

            _allTags = (List<Tag>)Tag.GetTags(CurrentNodeId, GroupName);
            LoadTags();
        }

        #region IUsercontrolDataEditor Members

        public object value
        {
            get
            {
                return _umbracoValue;
            }
            set
            {
                _umbracoValue = value.ToString();
            }
        }

        #endregion

        protected void AddTagsToNode()
        {
            Log_.Debug("Removing tags for node: " + CurrentNodeId);

            var tags = ActiveTags.Value;

            if (!string.IsNullOrEmpty(tags))
            {
                Log_.Error("no tags to add");
            }

            if (tags != null)
            {
                tags = tags.TrimEnd(new[] { ',' });
            }
            else
            {
                tags = string.Empty;
            }
            
            Log_.Debug("Tags: " + tags);

            Tag.RemoveTagsFromNode(CurrentNodeId, GroupName); // purge nodes

            // prevent adding blank tags in v4.5.2
            if (!string.IsNullOrEmpty(tags)) 
            {
                Tag.AddTagsToNode(CurrentNodeId, tags, GroupName);
            }

            _umbracoValue = tags;
        }

        private void LoadTags()
        {
            const string listItemFormat = "<li class=\"active user\"><input type=\"text\" name=\"gtTags_{0}\" class=\"tags active\" value=\"{1}\" /><span>x</span></li>";
            var builder = new StringBuilder();
            _allTags.Sort(new TagComparer());

            if (_allTags != null && _allTags.Count > 0)
            {
                for (int i = 0; i < _allTags.Count; i++)
                {
                    if (_allTags[i].TagCaption.Trim().Length > 0)
                    {
                        builder.AppendFormat(listItemFormat, i, _allTags[i].TagCaption);
                    }
                }
            }
            
            litExistingTags.Text = builder.ToString();
        }
    }
}